from flask import render_template,redirect,url_for,session, flash, request
from flask_login import login_required, current_user
#from flaskext.uploads import UploadSet, IMAGES
from bson.dbref import DBRef

from controller import app
from lib.form import Form

from dao.subject import SubjectDao
from dao.post import PostDao

from service.post import PostForm, PostService
import json

IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())

class PostsForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)




@app.route('/manage_posts')
@app.route('/manage_posts', methods=['GET','POST'])
@login_required
def manage_posts():
    form = PostForm()
    session['errors_json'] = ''
    if form.is_submitted():
        if form.has_error():
            session['errors_json'] = json.dumps(form.errors)
            return redirect(url_for('display_posts'))#errors_json=json.dumps(form.errors)))
        else:
            service = PostService()
            service.submit_post(form)
            return redirect(url_for('display_posts'))
    else:
        return redirect(url_for('display_posts'))

@app.route('/display_posts')
@login_required
def display_posts():
    #return render_template("add_post-v1.html", posts=None)

    if session['errors_json'] == '':
        errors = []
    else:
        errors = session['errors_json']
    
    service = PostService()
    user = service.get_current_user()
    _posts = service.get_post_list()
    return render_template("main_dashboard.html", errors_json=errors, posts=_posts, user=user)
    
@app.route("/delete_posts", methods=["GET", "POST"])
@login_required
def delete_posts():
    post_dao = PostDao()
    
    form = PostsForm()
    ids = form.request.form.getlist('selected')
    for _id in ids:
        post = post_dao.filter_first(id=int(_id))
        post_dao.remove_from_db(post)
        
    return render_template("manage_posts.html", posts=post_dao.all())            
